import { Chooser, ChooserResult } from '@awesome-cordova-plugins/chooser'; // 附件选择
import { Camera, CameraOptions } from '@awesome-cordova-plugins/camera'; // 拍照
import { FilePath } from '@awesome-cordova-plugins/file-path'; // 文件路径转换
import { FileOpener } from '@awesome-cordova-plugins/file-opener'; // 打开文件
import { 
  FileTransfer,
  FileUploadOptions,
} from '@awesome-cordova-plugins/file-transfer'; // 文件上传下载
import { File } from '@awesome-cordova-plugins/file'; // 文件夹地址信息
import {
  ImagePicker,
  ImagePickerOptions,
} from '@awesome-cordova-plugins/image-picker'; // 照片选择
import { Media, MediaObject } from '@awesome-cordova-plugins/media'; // 语音录制与语音播放
import { Geolocation } from '@awesome-cordova-plugins/geolocation'; // 语音录制与语音播放
import { BackgroundMode } from '@awesome-cordova-plugins/background-mode'; // 项目到后台运行提示语言
import { Device } from '@awesome-cordova-plugins/device'; // 设备信息
import { AppVersion } from '@awesome-cordova-plugins/app-version'; // 获取APP版本号等信息
import { alertController, isPlatform } from '@ionic/vue';
import { AppAvailability } from '@awesome-cordova-plugins/app-availability'; // 检查应用是否安装
import { WebIntent, IntentOptions } from '@awesome-cordova-plugins/web-intent'; // 唤醒应用
import { PublicService } from '@/utils/public';
import { actionSheetController, modalController } from '@ionic/vue';
import { InAppBrowser } from '@awesome-cordova-plugins/in-app-browser';
import { VideoEditor } from '@awesome-cordova-plugins/video-editor';
import { WebView } from '@awesome-cordova-plugins/ionic-webview';
import {
  MediaCapture,
  CaptureVideoOptions,
} from '@awesome-cordova-plugins/media-capture';
import { ScreenOrientation } from '@awesome-cordova-plugins/screen-orientation';
import { App } from '@capacitor/app';
import { Camera as camera, CameraResultType, CameraSource } from '@capacitor/camera';
import { Filesystem, Directory, Encoding } from '@capacitor/filesystem';
// const base64 = require('js-base64').Base64;
import configService from '@/utils/config';
import { Capacitor } from '@capacitor/core';
declare let cordova: any;
const publicService: PublicService = PublicService.getInstance();
/**
 * 定位返回信息
 */
export interface LocationInfo {
  addr?: string; //地址描述 "中国北京市海淀区马连洼街道旺科东路"
  coorType?: string; // 定位坐标类型 "gcj02"
  describe?: string; // 网络定位成功
  province?: string; //省 "北京市";
  city?: string; //市 "北京市"
  district?: string; //区县 "海淀区"
  street?: string; //街道 "旺科东路"
  latitude: number; // 纬度 40.04809
  longitude: number; // 经度 116.280415
  locType?: number; // 161
  locationdescribe?: string; //位置描述 "在中国国际服务外包新市场交易中心附近"
  operationers?: number; //0;
  radius?: number; // 100
  time?: string; // "2021-10-29 12:56:25";
}

/**
 * 设备信息
 */
export interface DeviceInfo {
  cordova?: string;
  model?: string;
  platform?: string;
  uuid?: string;
  version?: string;
  manufacturer?: string;
  isVirtual?: boolean;
  serial?: string;
}
export class NativeService {
  // 录音文件
  private audioFile!: MediaObject;
  private audioFilePath!: string; // 音频文件路径
  // 工具方法实例
  private static nativeService: NativeService;
  private locData = {
    latitude: 0,
    longitude: 0,
    city: '',
    district: '',
    address: '',
  };
  private loading: any;
  /**
   * 获取工具类实例
   * @param map 外部传入地图对象
   * @returns
   */
  public static getInstance(): NativeService {
    if (this.nativeService == null) {
      this.nativeService = new NativeService();
    }
    return NativeService.nativeService;
  }

  /**
   * 设置手机横竖屏
   * type landscape: 表示横屏显示  portrait: 表示竖屏显示
   */
  setScreenOrientation(type: string) {
    ScreenOrientation.lock(type); //表示竖屏显示
    // console.log(ScreenOrientation.type, 'ScreenOrientation.type ');
    // ScreenOrientation.unlock();    //屏幕解锁
    // ScreenOrientation.onChang
    // ScreenOrientation.lock(ScreenOrientation.type);
  }

  unlockScreenOrientation() {
    ScreenOrientation.unlock();
  }

  lockScreenOrientation() {
    ScreenOrientation.lock('portrait-primary'); //表示竖屏显示
    // ScreenOrientation.lock('landscape');
  }

  async setVideo(fileUri: string, outputFileName: string) {
    const videoInfo = await VideoEditor.getVideoInfo({ fileUri });
    console.log(videoInfo);
    let width: any;
    // const height: number;
    const ratio = videoInfo.width / videoInfo.height;
    if (ratio > 1) {
      width = videoInfo.width > 480 ? 480 : videoInfo.width;
    } else if (ratio < 1) {
      width = videoInfo.width > 360 ? 360 : videoInfo.width;
    } else if (ratio === 1) {
      width = videoInfo.width > 480 ? 480 : videoInfo.width;
    }
    const height = ((width / ratio).toFixed(0) as any) * 1;
    VideoEditor.transcodeVideo({
      fileUri,
      outputFileName,
      outputFileType: VideoEditor.OutputFileType.MPEG4,
      width,
      height,
    })
      .then((res) => {
        console.log(res);
      })
      .catch((err) => {
        console.log('错误', err);
      });
  }

  /**
   * 打开手机内置浏览器
   * @param url
   */
  createBrowser(url: string) {
    InAppBrowser.create(url, '_system', 'location=yes,hidden=yes');
    // console.log(cordova);
    // console.log(window);
    // (cordova as any).InAppBrowser.open(url, '_system');
  }

  /**
   * 检查应用是否安装
   * @param packageName 包名
   * @returns
   */
  checkAppAvailability(packageName: string): Promise<any> {
    // AppAvailability.check(packageName).then((res) => {
    //   console.log(res)
    // }).catch((error) => {
    //   console.log('error', error)
    // });
    // console.log('packageName', packageName);
    return new Promise((resolve, reject) => {
      AppAvailability.check(packageName)
        .then((res) => {
          // console.log('packageNameres', res);
          resolve(res);
        })
        .catch((err) => {
          // console.log('packageNameerr', err);
          reject(err);
        });
    });
  }

  /**
   * 唤醒应用
   */
  openWebIntent(opts: IntentOptions) {
    opts.action = WebIntent.ACTION_VIEW;
    WebIntent.startActivity(opts);
  }

  /**
   * 获取APP版本号
   * @returns
   */
  getAppVersion(): Promise<any> {
    return new Promise((resolve, reject) => {
      AppVersion.getVersionNumber().then((res) => {
        resolve(res);
      });
    });
  }

  /**
   * 获取设备信息
   */
  getDeviceInfo(): Promise<any> {
    return new Promise((resolve, reject) => {
      resolve(Device);
    });
  }

  /**
   * 设置项目到后台运行提示语言
   * title 标题
   * text 提示的文字
   */
  setBackgroundMode(title: string, text: string) {
    BackgroundMode.setDefaults({
      title,
      text,
    });
    BackgroundMode.enable();
  }

  /**
   * 开始定位
   */
  async startLoc(): Promise<any> {
    return new Promise((resolve, reject) => {
      if (isPlatform('ios')) {
        const posOptions = { enableHighAccuracy: true };
        Geolocation.getCurrentPosition(posOptions)
          .then((resp) => {
            // alert('ios获取到的位置'+JSON.stringify(resp));
            const lat = resp.coords.latitude;
            const lng = resp.coords.longitude;
            // const pos = {
            //   lat: lat,
            //   lon: lng,
            // };
            if (lat !== 5e-324 && lng !== 5e-324) {
              this.locData.latitude = lat;
              this.locData.longitude = lng;
              // this.locData.city = resp.coords.city;
              // this.locData.district = resp.coords.district;
            }
            resolve(this.locData);
          })
          .catch((err) => {
            // this.locData.address = '这是地址';
            resolve(this.locData);
            // console.log(err)
            // reject(err)
          });
      } else {
        try {
          (window as any).navigator.baidulocation.get(
            (message: any) => {
              console.log(message);
              const lat = message.latitude;
              const lng = message.longitude;
              if (lat !== 5e-324 && lng !== 5e-324) {
                // 'lat': wgsLat, 'lon': wgsLon
                // const loc = this.gcj_decrypt_exact(lat, lng);
                this.locData.latitude = lat;
                this.locData.longitude = lng;
                this.locData.city = message.city;
                this.locData.district = message.district;
                this.locData.address = message.addr;
              }
              resolve(this.locData);
            },
            (err: any) => {
              // alert(JSON.stringify(err) + 'err');
              reject(err);
            },
            true
          );
        } catch (error) {
          resolve((window as any).defaultLocationCountyInfos);
        }
      }
    });
  }

  /**
   * 获取文件的大小
   */
  getFileSize(filePath: string): Promise<any> {
    return new Promise((resolve, reject) => {
      File.resolveLocalFilesystemUrl(filePath)
        .then((fileEntry) => {
          fileEntry.getMetadata((res) => {
            resolve(res);
          });
        })
        .catch((error) => {
          console.log(error);
          reject('error');
        });
    });
  }

  /**
   * 创建文件
   * @param filePath 文件路径
   * @param fileName 文件名称
   * @returns
   */
  createFile(filePath: string, fileName: string): Promise<any> {
    return new Promise((resolve, reject) => {
      File.createFile(filePath, fileName, true)
        .then((res) => {
          resolve(filePath.replace(/^file:\/\//, '') + fileName);
        })
        .catch((e: any) => {
          console.log(e, '文件报错失败');
          reject('error');
        });
    });
  }

  /**
   * 开始录制语音
   * @returns
   */
  startRecord(): Promise<any> {
    return new Promise((resolve, reject) => {
      const fileName =
        Math.ceil(Math.random() * 100000000) +
        '' +
        new Date().getTime() +
        '.mp3';
      this.createFile(File.dataDirectory, fileName).then(async (res) => {
        this.audioFilePath = File.dataDirectory + fileName;
        this.audioFile = Media.create(
          File.dataDirectory.replace(/^file:\/\//, '') + fileName
        );
        this.audioFile.startRecord();
        resolve({ fileName, filePath: this.audioFilePath });
      });
    });
  }

  /**
   * 停止录音
   */
  stopRecord(): Promise<any> {
    return new Promise((resolve, reject) => {
      this.audioFile.stopRecord();
      if (this.audioFile) {
        this.filePath(this.audioFilePath).then((path) => {
          resolve(path);
        });
      } else {
        reject('');
      }
    });
  }

  setConvertFileSrc(filePath: string): Promise<any> {
    return new Promise((resolve, reject) => {
      resolve(WebView.convertFileSrc(filePath));
    });
  }

  async addImgFile(
    callback: (arg0: any, arg1?: string, arg2?: string | undefined) => void,
    ThsAudio?: any
  ) {
    const actionSheet = await actionSheetController.create({
      header: '照片选择',
      buttons: [
        {
          text: '拍照',
          handler: () => {
            // BackgroundMode.enable();
            camera.getPhoto({
              quality: 100,
              allowEditing: false, 
              width:1080,
              height:1920,
              resultType: CameraResultType.Uri,   //返回文件路径
              source: CameraSource.Camera, //配置相机拍照还是相册选择
            }).then((res: any) => {
              console.log(res);
              callback(res.path, 'photo');
            })
            // this.camera({
            //   quality: 100,
            //   destinationType: 1,
            //   sourceType: 1,
            //   targetWidth: 1080,
            //   targetHeight: 1920,
            //   mediaType: 0,
            //   encodingType: 1,
            // })
            //   .then(async (res) => {
            //     console.log(res);
            //     // BackgroundMode.disable();
            //     const path = await this.setConvertFileSrc(res);
            //     // console.log(path);
            //     callback(res, 'photo');
            //   })
            //   .catch((err) => {
            //     // BackgroundMode.disable();
            //     console.error(err);
            //   });
          },
        },
        {
          text: '相册',
          handler: () => {
            this.camera({
              quality: 100,
              destinationType: 1,
              sourceType: 2,
              targetWidth: 1080,
              targetHeight: 1920,
              mediaType: 0,
              encodingType: 1,
            })
              .then(async (res) => {
                console.log(res);
                // BackgroundMode.disable();
                const path = await this.setConvertFileSrc(res);
                // console.log(path);
                callback(res, 'photo');
              })
              .catch((err) => {
                // BackgroundMode.disable();
                console.error(err);
              });
            // this.slectImagePicker({
            //   maximumImagesCount: max,
            //   quality: 50,
            // })
            //   .then((res) => {
            //     // BackgroundMode.disable();
            //     callback(res, 'img');
            //   })
            //   .catch(() => {
            //     // BackgroundMode.disable();
            //   });
          },
        },
        {
          text: '取消',
          role: 'cancel',
          handler: () => {
            console.error('Cancel clicked');
          },
        },
      ],
    });
    await actionSheet.present();
  }

  async addMP4File(
    max: number,
    callback: (arg0: any, arg1: string, arg2?: string | undefined) => void,
    ThsAudio?: any
  ) {
    const actionSheet = await actionSheetController.create({
      header: '视频选择',
      buttons: [
        {
          text: '拍摄视频',
          handler: async () => {
            // this.setMediaCapture();
            // BackgroundMode.enable();
            const mediafile = await this.startVideo();
            const res = await this.getFileSize(mediafile.fullPath);
            const fileSize = res.size / 1024 / 1024;
            if(fileSize > 100){
              publicService.thsToast('文件大于100M，请重新选择上传');
              return;
            }
            callback(mediafile.fullPath, 'video');
          },
        },
        {
          text: '选择视频',
          handler: () => {
            this.camera({
              destinationType: 1,
              quality: 50,
              sourceType: 0,
              mediaType: 1,
            })
              .then(async (res) => {
                console.log(res,'-------选择视频------');
                const fileName = Math.ceil(Math.random() * 100000000) +
                '' +
                new Date().getTime() +
                '.' +
                this.getFileSuffix(res);
        //         fileName
        // .substring(fileName.lastIndexOf('/') + 1, fileName.length)
                Filesystem.stat({path: res}).then((res1: any) => {
                  console.log(res1, File.cacheDirectory, res1.uri.substring(res1.uri.lastIndexOf('/') + 1, res1.uri.length), '-------选择视频------');
                  if(res1.size / 1000000 > 100){
                    publicService.thsToast('文件大于100M，请重新选择上传');
                    return;
                  }
                  callback(
                    res,
                    'video',
                    res1.uri.substring(res1.uri.lastIndexOf('/') + 1, res1.uri.length),
                  );
                }).catch((e: any) => {
                  publicService.thsToast('文件大小获取失败，请重新选择上传');
                  console.log(e)
                })
                // this.trimVideo(res, callback);
              })
              .catch((err) => {
                // BackgroundMode.disable();
                console.log(err,'-----11----');
              });
          },
        },
        {
          text: '取消',
          role: 'cancel',
          handler: () => {
            console.error('Cancel clicked');
          },
        },
      ],
    });
    await actionSheet.present();
  }

  async addFile(
    max: number,
    callback: (arg0: any, arg1: string, arg2?: string | undefined) => void,
    ThsAudio?: any
  ) {
    const actionSheet = await actionSheetController.create({
      header: '附件类型选择',
      buttons: [
        {
          text: '拍照',
          handler: () => {
            BackgroundMode.enable();
            this.camera({
              quality: 100,
              destinationType: 1,
              sourceType: 1,
              targetWidth: 1080,
              targetHeight: 1920,
              mediaType: 0,
              encodingType: 1,
            })
              .then(async (res) => {
                BackgroundMode.disable();
                const path = await this.setConvertFileSrc(res);
                // console.log(path);
                callback(path, 'photo');
              })
              .catch((err) => {
                // BackgroundMode.disable();
                console.error(err);
              });
          },
        },
        {
          text: '相册',
          handler: () => {
            this.slectImagePicker({
              maximumImagesCount: max,
              quality: 50,
            })
              .then((res) => {
                // BackgroundMode.disable();
                callback(res, 'img');
              })
              .catch(() => {
                // BackgroundMode.disable();
              });
          },
        },
        {
          text: '录制音频',
          handler: async () => {
            const modal = await modalController.create({
              component: ThsAudio as any,
              cssClass: 'enlarge-image-modal',
            });
            await modal.present();
            const res = await modal.onDidDismiss();
            if (res.data.filePath) {
              callback(res.data.filePath, 'video');
            }
          },
        },
        {
          text: '拍摄视频',
          handler: async () => {
            BackgroundMode.enable();
            const mediafile = await this.startVideo();
            const res = await this.getFileSize(mediafile.fullPath);
            const fileSize = res.size / 1024 / 1024;
            callback(mediafile.fullPath, 'video');
          },
        },
        {
          text: '选择视频',
          handler: () => {
            
            this.camera({
              destinationType: 1,
              quality: 50,
              sourceType: 0,
              mediaType: 1,
            })
              .then(async (res) => {
                callback(
                  res,
                  'video',
                  Math.ceil(Math.random() * 100000000) +
                  '' +
                  new Date().getTime() +
                  '.' +
                  this.getFileSuffix(res)
                );
                // this.trimVideo(res, callback);
              })
              .catch((err) => {
                // BackgroundMode.disable();
                console.log(err);
              });
          },
        },
        {
          text: '取消',
          role: 'cancel',
          handler: () => {
            console.error('Cancel clicked');
          },
        },
      ],
    });
    await actionSheet.present();
  }

  // /**
  //  * 视频剪切
  //  * @param filePath
  //  */
  // trimVideo(filePath: string, callback) {
  //   (window as any).plugins.videoTrim.trimVideo(filePath, (res) => {
  //     console.log(res)
  //     callback(res);
  //   }, (error) => {
  //     console.log(error)
  //   });
  // }

  /**
   * 选择文件
   * @param accept
   * @returns
   */
  chooserFile(accept?: any): Promise<any> {
    // BackgroundMode.enable();
    return new Promise((resolve, reject) => {
      Chooser.getFile(accept)
        .then(async (res: any) => {
          console.log(res);
          // alert(JSON.stringify(res));
          // BackgroundMode.disable();
          // const resSize = await this.getFileSize(res.uri);
          // const fileSize = resSize.size / 1024 / 1024;
          // if (fileSize > 20) {
          //   publicService.thsToast('文件过大，请重新选择');
          //   reject('error');
          //   return;
          // }
          Filesystem.stat({path: res.uri}).then((res1: any) => {
            console.log(res1, File.cacheDirectory, res1.uri.substring(res1.uri.lastIndexOf('/') + 1, res1.uri.length), '-------选择文件------');
            if(res1.size / 1000000 > 100){
              publicService.thsToast('文件大于100M，请重新选择上传');
              return;
            }
            resolve(res);
          }).catch((e: any) => {
            publicService.thsToast('文件大小获取失败，请重新选择上传');
            reject('error');
          })
        })
        .catch((error) => {
          // BackgroundMode.disable();
          reject('error');
        });
    });
  }

  /**
   * 拍照
   * @param opts
   * @returns
   */
  camera(opts: CameraOptions): Promise<any> {
    return new Promise((resolve, reject) => {
      Camera.getPicture(opts)
        .then((res: ChooserResult) => {
          resolve(res);
        })
        .then((error) => {
          // console.log('视频选择', error)
          reject('error');
        });
    });
  }

  /**
   * 手机选择文件，转换为可上传的文件路径
   * @param path  文件路径
   * @returns
   */
  filePath(path: string): Promise<any> {
    return new Promise((resolve, reject) => {
      FilePath.resolveNativePath(path)
        .then((res: string) => {
          resolve(res);
        })
        .then((error) => {
          reject('error');
        });
    });
  }

  /**
   * 打开文件
   * @param filePath 文件存储路径
   * @param fileMIMEType 文件打开方式
   */
  fileOpener(filePath: string, fileMIMEType: string) {
    FileOpener.open(filePath, fileMIMEType)
      .then((res: any) => {
        console.log(res);
      })
      .catch((error: any) => {
        publicService.thsToast('文件打开失败，请重试');
      });
  }

  /**
   * 文件上传
   * @param fileUrl 文件路径
   * @param url 服务器地址
   * @param opts 配置项
   * @returns
   */
  fileLoad(
    fileUrl: string,
    url: string,
    opts: FileUploadOptions
  ): Promise<any> {
    // if (!this.loading) {
    //   this.loading = publicService.Thsloading('附件上传中，请稍等。。。');
    // }
    return new Promise((resolve, reject) => {
      const file = FileTransfer.create();
      file
        .upload(fileUrl, url, opts)
        .then((res: any) => {
          // alert(JSON.stringify(res));
          console.log(res);
          publicService.closeLoading(this.loading);
          this.loading = null;
          // console.log(res);
          resolve(JSON.parse(res.response));
        })
        .catch((err: any) => {
          // alert(JSON.stringify(err));
          console.log(err, 'fileLoad');
          publicService.closeLoading(this.loading);
          this.loading = null;
          // publicService.thsToast('附件上传失败，请重试');
          reject('error');
        });
    });
  }

  /**
   * 检查文件是否存在
   * @param fileName 文件名称
   * @param filePath 文件本地路径
   * @param callback 回调函数
   */
  checkFileExitStatus(
    fileName: string,
    filePath: string,
    callback: { (res: any): void; (arg0: boolean): void }
  ) {
    try {
      File.checkFile(filePath, fileName)
        .then(() => {
          callback(true);
        })
        .catch((err) => {
          callback(false);
        });
    } catch (error) {
      callback(false);
    }
  }

  /**
   * 附件下载
   * @param fileUrl 文件路径
   */
  fileDown(
    fileUrl: string,
    fileName: string,
    checkFile?: boolean,
    ThsloadingMsg = '附件下载中，请稍等。。。'
  ): Promise<any> {
    console.log(fileUrl);
    return new Promise((resolve, reject) => {
      const mimeType = this.getFileMimeType(fileName);
      this.checkFileExitStatus(fileName, File.dataDirectory, (res) => {
        if (res && checkFile) {
          publicService.thsPromptAlert(
            '温馨提示',
            '文件已经存在，是否确认打开？',
            () => {
              this.fileOpener(File.dataDirectory + fileName, mimeType);
            }
          );
        } else {
          const fileTransfer = FileTransfer.create();
          if (!this.loading) {
            this.loading = publicService.Thsloading(ThsloadingMsg);
          }
          fileTransfer
            .download(encodeURI(fileUrl), File.dataDirectory + fileName)
            .then(() => {
              publicService.closeLoading(this.loading);
              this.loading = null;
              if (checkFile) {
                publicService.thsPromptAlert(
                  '温馨提示',
                  '文件已下载完毕，是否确认打开？',
                  () => {
                    this.fileOpener(File.dataDirectory + fileName, mimeType);
                  }
                );
              } else {
                this.fileOpener(File.dataDirectory + fileName, mimeType);
              }
            })
            .catch((res) => {
              publicService.thsToast('文件下载失败，请重试');
              publicService.closeLoading(this.loading);
              this.loading = null;
            });
        }
      });
    });
  }

  /**
   * 根据文件名称获取文件媒体类型
   * @param fileName 文件名称
   */
  getFileMimeType(fileName: string) {
    const fileSuffix = this.getFileSuffix(fileName);
    let mimeType = '';
    switch (fileSuffix) {
      case 'txt':
        mimeType = 'text/plain';
        break;
      case 'docx':
        mimeType =
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        break;
      case 'doc':
        mimeType = 'application/msword';
        break;
      case 'pptx':
        mimeType =
          'application/vnd.openxmlformats-officedocument.presentationml.presentation';
        break;
      case 'ppt':
        mimeType = 'application/vnd.ms-powerpoint';
        break;
      case 'xlsx':
        mimeType =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        break;
      case 'xls':
        mimeType = 'application/vnd.ms-excel';
        break;
      case 'zip':
        mimeType = 'application/x-zip-compressed';
        break;
      case 'rar':
        mimeType = 'application/octet-stream';
        break;
      case 'pdf':
        mimeType = 'application/pdf';
        break;
      case 'jpg':
        mimeType = 'image/jpeg';
        break;
      case 'png':
        mimeType = 'image/png';
        break;
      case 'apk':
        mimeType = 'application/vnd.android.package-archive';
        break;
      default:
        mimeType = 'application/' + fileSuffix;
        break;
    }
    return mimeType;
  }

  /**
   * 根据文件名称截取文件后缀名
   * @param fileName 文件名
   */
  getFileSuffix(fileName: string) {
    if (fileName) {
      return fileName
        .substring(fileName.lastIndexOf('.') + 1, fileName.length)
        .toLowerCase();
    }
  }

  /**
   * 照片选择
   * @param opts
   * @returns
   */
  slectImagePicker(opts: ImagePickerOptions): Promise<any> {
    return new Promise((resolve, reject) => {
      ImagePicker.getPictures(opts)
        .then((res: any) => {
          resolve(res);
        })
        .catch(() => {
          reject('error');
        });
    });
  }

  setMediaCapture(): Promise<any> {
    return new Promise((resolve, reject) => {
      MediaCapture.captureVideo({
        limit: 1,
        duration: 10,
        quality: 50,
      })
        .then((res: any) => {
          console.log(res);
          resolve(res[0]);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  /**
   * 开始录制视频
   * @returns
   */
  startVideo(): Promise<any> {
    return new Promise((resolve, reject) => {
      (window as any).plugins.videocaptureplus.captureVideo(
        (res: any[]) => {
          // BackgroundMode.disable();
          resolve(res[0]);
        },
        (err: any) => {
          // BackgroundMode.disable();
          reject(err);
        },
        {
          limit: 1,
          duration: 15,
          highquality: true,
        }
      );
    });
  }

  /**
   * 下载APP
   * @param filename 文件名称
   * @param content 提示内容
   * @param packagename 包名
   */
  async downApp(
    content: string,
    packagename: string,
    appurl: string,
    update?: string,
    status?: any
  ): Promise<any> {
    const alert1 = await alertController.create({
      header: update ? '发现新版本，是否更新？' : '温馨提示',
      message: update ? content : content,
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary cancelBtn',
          handler: () => {
            if (status && status === '1') {
              try {
                App.exitApp();
              } catch (error) {
                // this.appMinimize.minimize();
              }
            } else {
              alert1.dismiss();
            }
          },
        },
        {
          text: '确认',
          handler: () => {
            alert1.dismiss();
            this.fileDown(appurl, packagename, false, '下载中，请稍等。。。');
          },
        },
      ],
    });
    await alert1.present();
  }
}
